<script setup lang="ts">
import { ref } from "vue";
const cursor = ref<HTMLElement | null>(null);
const format = (cmd: "bold" | "italic" | "underline") => {
  // Selection、Range
  const selection = window.getSelection();
  console.log("🚀 ~ format ~ selection:", selection);

  // 清空选取
  // selection?.removeAllRanges();

  // 获取选取范围
  // selection?.rangeCount 可以拿到 rangeCount
  const range = selection?.getRangeAt(0);
  console.log("🚀 ~ format ~ range:", range);

  // 获取当前选中内容
  const dom = range?.extractContents(); // 提取当前选中内容
  console.log("🚀 ~ format ~ dom:", dom);

  let wrapper;

  switch (cmd) {
    case "bold":
      wrapper = document.createElement("strong");
      break;
    case "italic":
      wrapper = document.createElement("em");
      break;
    case "underline":
      wrapper = document.createElement("u");
      break;
  }

  wrapper.appendChild(dom!);

  // 通过 range 追加到 dom 中，并且保持选中状态
  range?.insertNode(wrapper);

  // // 当前选取的范围
  // const rect = range?.getBoundingClientRect();
  // console.log("🚀 ~ format ~ rect:", rect);

  // if (rect) {
  //   const { left, top } = rect;
  //   cursor.value!.style.left = `${left}px`;
  //   cursor.value!.style.top = `${top}px`;
  //   cursor.value!.style.opacity = "1";
  // }
};

// document.addEventListener("selectionchange", () => {})
</script>

<template>
  <!-- <input /> -->
  <!-- <textarea></textarea> -->
  <button @click="format('bold')">加粗</button>
  <button @click="format('italic')">斜体</button>
  <button @click="format('underline')">下划线</button>
  <div class="editor-container">
    <div class="editor-content" contenteditable="true"></div>
    <div class="cursor" ref="cursor"></div>
  </div>
</template>

<style scoped>
.editor-container {
  position: relative;
}
.editor-content {
  width: 100%;
  border: 1px solid #ccc;
  min-height: 200px;
  padding: 10px;
}
.cursor {
  opacity: 0;
  position: absolute;
  width: 1px;
  height: 20px;
  background-color: #333;
}
</style>
